<template>
	<view class="gauge-box">
		<canvas :canvas-id="config.id" :style="{'width' : _width + 'px','height' : _width + 'px'}"></canvas>
	</view>
</template>

<script>
const mainDefault = {
	bgColor:'transparent',
	startAngle: 1.5,
	endAngle: 0,
	ringWidth: uni.upx2px(469),
	width:uni.upx2px(406),
	lineLong:uni.upx2px(24),
	ringWid:uni.upx2px(28),
	ringColor:'#E7F0FE',
	padding: 0,
	min: 0,
	max: 100,	
	value: 0,
	unit: false,
	name: '信用度一般',
	detail:{},
	axisTick:[]
};
const detailDefault = {//标题、数值、单位设置
	score: {//score 信用分
		offsetCenter:[0,uni.upx2px(-20)],//距离圆心直径偏移
		color:'#0058bc',
		fontSize: uni.upx2px(112),
		fontWeight:'normal',
		textAlign:'center'
	},
	creditDes: {//信用描述 
		color:'#6C87BF',
		fontSize: uni.upx2px(36),
		fontWeight:'bolder',
		offsetCenter:[0,uni.upx2px(93.5)],//距离圆心直径偏移
		textAlign:'center'
	},
	evaluationTime: {
		color:'#6C87BF',
		fontSize: uni.upx2px(30),
		fontWeight:'normal',
		offsetCenter:[0,uni.upx2px(93.5)],//距离圆心直径偏移
		// offsetCenter:[0,uni.upx2px(134.5)],//距离圆心直径偏移
		textAlign:'center'
	}
};
const axisTickDefault = {//轴刻度线
	width: uni.upx2px(24),//轴长
	number: 200,//轴数量（相当于几等分）
	color: '#C9DEFF',//轴颜色(第一个值--指针之前的颜色，之后的颜色)
	// subNumber: 10,//大刻度之间分成几个小刻度
	subWidth:  uni.upx2px(6),
	subHeight:  1,
	padding: uni.upx2px(29)//刻度距离边距
};
export default {
	data:function(){
		return {
			gaugeOption:{}
		}
	},
	props:{
		config:{
			type: Object,
			default:() => {
				return {};
			}
		},
		bgColor:{
			type: String,
			default:'#fff'
		}
	},
	computed:{
		_width:function(){
			return mainDefault.ringWidth+mainDefault.ringWid+1
		},
		_status:function(){
			return String(this.config.status) !== 'false' ? true : false;
		},
		_dStatus:function(){
			return String(this.config.status) === 'true' || this.config.status === 1 ? 1 : 0;
		}
	},
	watch:{
		config:{
			handler(newVal, oldVal) {
				this.initCharts();
			},
			deep: true
		}
	},
	mounted:function(){
		this.initCharts();
	},
	methods: {
		initCharts:function(){
			// 自动填充数据
			var gaugeOption = this.fillInData();
			var uChartsGauge = null;
			uChartsGauge = uni.createCanvasContext(gaugeOption.id, this);
			uChartsGauge.fillStyle = gaugeOption.bgColor;
			uChartsGauge.fillRect(0,0,gaugeOption.width,gaugeOption.width);
			uChartsGauge.save();
			var centerPosition = {
				x: (mainDefault.ringWidth+mainDefault.ringWid+1) / 2,
				y: (mainDefault.ringWidth+mainDefault.ringWid+1) / 2
			};
			this.drawGauge(gaugeOption,uChartsGauge,centerPosition);
			// this.initDate(gaugeOption,centerPosition);
		},
		drawGauge:function(options,ctx,centerPosition){
			var centerPosition = {
				x: (mainDefault.ringWidth+mainDefault.ringWid+1) / 2,
				y: (mainDefault.ringWidth+mainDefault.ringWid+1) / 2
			};
			// 总角度数（为什么要加1）假装下图是个圆  0.75PI ~ 0.25PI 实际间隔1.5PI 
					//   1.5PI
					//     ——
			  // 1.0PI	|	   |  0PI
					//     ——
					//   0.5PI
			var totalAngle = options.startAngle - options.endAngle + 1;
			// 计算半径
			var radius = options.width/2;
			
			console.log(options.axisTick)
			console.log(options.axisTick.length)
			//画刻度线
			// for(let idx = 0,len = options.axisTick.length;idx < len;idx++){
				var gaugeOption = options.axisTick[0];
				console.log(gaugeOption)
				// radius -= (gaugeOption.padding + gaugeOption.width / 2);
				var criticalPoint = Math.floor(options.value / (options.max / gaugeOption.number));//大刻度临界点
				var colors = gaugeOption.color.split(',');
				colors[1] = colors[1] || colors[0];
				var splitAngle = totalAngle / gaugeOption.number;
				var startX = -radius - gaugeOption.width * 0.5;
				var endX = -radius - gaugeOption.width * 0.5 + gaugeOption.width;
				
				// 画大刻度
				let maxScaleData = {
					...centerPosition,
					startX,
					endX,
					splitAngle,
					criticalPoint,
					colors,
					startAngle: options.startAngle,
					width: gaugeOption.subHeight,
					number: gaugeOption.number,
				}
				console.log(maxScaleData);
				this.drawScale(ctx, maxScaleData);
				//画圆圈
				let ringData = {
					...centerPosition,
					r:options.ringWidth/2,
					lineR:options.ringWid,
					color:options.ringColor
				}
				console.log("画圆："+ringData.toString());
				console.log(ringData);
				this.drawRing(ctx, ringData);
				this.drawLine(ctx, ringData);
				var _fillText = (options.value * 1) === 0 ? 0 : options.value;
				let ProgressBarData = {
					...ringData,
					fs:_fillText
				}
				this.drawProgressBar(ctx, ProgressBarData);
			// }
			// 信用分
			var titleObj = {
				...options.detail.score,
				...centerPosition,
				name: _fillText
			}
			this.drawText(ctx,titleObj);
			
			// 信用度
			// var valueObj = {
			// 	...options.detail.creditDes,
			// 	...centerPosition,
			// 	name: options.name
			// }
			// this.drawText(ctx,valueObj);
			
			// 评估时间
			let newDate = new Date();
			let pgsj = newDate.getFullYear()+'.'+(newDate.getMonth()+1)+'.'+newDate.getDate();
			let nameText = '评估于'+pgsj;
			if(options.value==0){
				nameText = '信用分查询中...';
			}
			var valueObj = {
				...options.detail.evaluationTime,
				...centerPosition,
				name: nameText
			}
			this.drawText(ctx,valueObj);
			
			ctx.draw();
		},
		// 画字
		drawText:function(ctx,data){
			let { fontSize, fontWeight, color, textAlign, offsetCenter, x, y, name } = data;
			// 画标题
			ctx.beginPath();
			// 设置字体
			ctx.font = fontSize + "px MicrosoftYaHei "+ fontWeight;
			// 设置颜色
			ctx.fillStyle = color;
			// 设置水平对齐方式
			ctx.textAlign = textAlign;
			// 设置中心点
			ctx.translate(x, y);
			// 绘制文字（参数：要写的字，x坐标，y坐标）
			ctx.fillText(name,...offsetCenter);
			ctx.closePath();
			ctx.stroke();
			ctx.restore();
			ctx.save();
		},
		//画线
		drawLine:function(ctx,data){
			let {x,y,r,color,lineR} = data;
			ctx.translate(x, y);
			ctx.beginPath();
			ctx.setStrokeStyle('#BBD1F3');
			ctx.setLineWidth(uni.upx2px(1));
			ctx.moveTo(-uni.upx2px(150),uni.upx2px(29.5));
			ctx.lineTo(uni.upx2px(150),uni.upx2px(29.5));
			ctx.stroke();
			// 清除状态
			ctx.restore();
			ctx.save();
		},
		//画圈
		drawRing:function(ctx,data){
			let {x,y,r,color,lineR} = data;
			ctx.translate(x, y);
			ctx.rotate(-90 * Math.PI/180);
			ctx.beginPath();
			ctx.setStrokeStyle(color);
			ctx.setLineWidth(lineR);
			ctx.arc(0,0,r,0,2*Math.PI);
			ctx.stroke();
			// 清除状态
			ctx.restore();
			ctx.save();
		},
		//画进度
		drawProgressBar:function(ctx, data,centerPosition){
			let {x,y,r,color,lineR,fs} = data;
			console.log({x,y,r,color,lineR,fs});
			ctx.translate(x, y);
			ctx.rotate(-90 * Math.PI/180);
			ctx.beginPath();
			var ds = fs/1000*360;
			var g = ctx.createLinearGradient(r,0,r*Math.cos(ds*Math.PI/180),r*Math.sin(ds*Math.PI/180));
			g.addColorStop(0, '#4E8DF1');
			// g.addColorStop(0.25,'#0199f0');
			// g.addColorStop(0.5,'#00b3f0');
			// g.addColorStop(0.75,'#00ccf0');
			g.addColorStop(1, '#4ADDEE');
			ctx.setStrokeStyle(g);
			// ctx.moveTo(-startX,0);
			// ctx.lineTo(startX,0);
			ctx.setLineWidth(lineR);
			ctx.arc(0,0,r,0,ds*Math.PI/180);
			ctx.stroke();
			// 清除状态
			ctx.restore();
			ctx.save();
			//画开始圆点
		
			let startDots = {
				x,
				y:y-r,
				color:'#4E8DF1',
				r:lineR/2
			}
			this.drawDots(ctx,startDots);
			let smStartDots = {
				x,
				y:y-r,
				color:'#ffffff',
				r:uni.upx2px(5)/2
			}
			this.drawDots(ctx,smStartDots);
			//画结束圆点
			if(ds>0){
				let endDots = {
					x:r*Math.cos(ds*Math.PI/180),
					y:r*Math.sin(ds*Math.PI/180),
					color:'#4ADDEE',
					r:lineR/2
				}
				ctx.translate(x, y);
				ctx.rotate(-90 * Math.PI/180);
				this.drawDots(ctx,endDots,true);
			}
		},
		//画圆点
		drawDots:function(ctx, data,isEndDots){
			console.log(data);
			let {x,y,r,color,lineR} = data;
			if(isEndDots){
				// var c = ctx.getImageData(x, y, 1, 1).data;
			}
			ctx.beginPath();
			ctx.setStrokeStyle(color);
			ctx.setLineWidth(1);
			ctx.arc(x,y,r,0,2*Math.PI);
			ctx.fillStyle=color;//填充颜色,默认是黑色
			ctx.fill();//画实心圆
			// cxt.closePath();
			// 清除状态
			ctx.restore();
			ctx.save();
		},
		// 画刻度
		drawScale:function(ctx, data){
			let { number, criticalPoint, startX, endX, splitAngle, width, x, y, startAngle,colors } = data;
			// 设置中心点
			ctx.translate(x, y);
			ctx.rotate((startAngle - 1) * Math.PI);
			for (let i = 0; i <= number; i++) {
				ctx.beginPath();
				ctx.setStrokeStyle(i <= criticalPoint ? colors[0] : colors[1]);
				ctx.setLineWidth(width);
				ctx.moveTo(startX, 0);
				ctx.lineTo(endX, 0);
				ctx.stroke();
				ctx.rotate(splitAngle * Math.PI);
			}
			// 清除状态
			ctx.restore();
			ctx.save();
		},
		fillInData:function(){
			var gaugeOption = this.deepClone(mainDefault, this.config)
			for(var _k in detailDefault){
				gaugeOption.detail[_k] = this.deepClone(detailDefault[_k], gaugeOption.detail[_k])
			}
			if(gaugeOption.axisTickLength === undefined || gaugeOption.axisTickLength === null){
				if(!(gaugeOption.axisTick instanceof Array)){
					gaugeOption.axisTick = [gaugeOption.axisTick]
				}
			}else{
				gaugeOption.axisTick = gaugeOption.axisTick || [];
			}
			var axisTickLength = 1;
			var axisTick = [].concat(gaugeOption.axisTick);
			for(var idx = 0,len = axisTickLength;idx < len;idx++){
				var defaultData = axisTickDefault;
				axisTick[idx] = axisTick[idx] || {};
				if(idx > 0 && !axisTick[idx].padding){
					axisTick[idx].padding = +axisTick[idx -1].width;
				}
				axisTick[idx] = this.deepClone(defaultData, axisTick[idx]);
			}
			gaugeOption.axisTick = axisTick
			return gaugeOption;
		},
		deepClone:function(source,target){//待优化代码
			var _obj = {};
			source = source || {};
			target = target || {};
			Object.assign(_obj, source, target);
			return JSON.parse(JSON.stringify(_obj));
		}
	}
};
</script>

<style>
	.gauge-box {
		position: relative;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
	}
	.gauge-box canvas{
		width: 100%;
		margin: 0 auto;
		height: auto;
		display: block;
	}
</style>
